package com.flycat.controller;

import com.flycat.common.constants.Constants;
import com.flycat.core.Result;
import com.flycat.core.ResultGenerator;
import com.flycat.dto.KV;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * Created by linkun on 2017/10/18.
 */
@RestController
@RequestMapping("/static")
public class ImageController {

    private static final Logger logger = LoggerFactory.getLogger(ImageController.class);


    private String imagePath = "/tmp/static/images/";


    @RequestMapping(value = "/images/{name}.{pre}")
    public void createFolw(HttpServletResponse response,
                             @PathVariable("name") String name,
                             @PathVariable("pre") String pre) {
        // response.setContentType("image/*");
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(imagePath + name + Constants.POINT + pre);
            os = response.getOutputStream();
            int count;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value="/upload",method= RequestMethod.POST)
    public Result<KV> fildUpload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request)throws Exception{
        //获得物理路径webapp所在路径
        String pathRoot = "/tmp";//request.getSession().getServletContext().getRealPath("");
        logger.info("存储图片的根路径为:pathRoot:{}",pathRoot);
        String path="";
        if(!file.isEmpty()){
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType=file.getContentType();
            //获得文件后缀名称
            String imageName=contentType.substring(contentType.indexOf("/")+1);
            path = imagePath + uuid + Constants.POINT + imageName;
            file.transferTo(new File(path));
        }
        KV kv = new KV();
        kv.setKey("imagePath");
        kv.setValue(path);
        return ResultGenerator.genSuccessResult(kv);
    }
}
